# -*- coding: utf-8 -*-
# @Time : 2025/10/23 14:48:37
# @Desc :生成客户端主窗口
# @Author : Sean
# @File   : main.py
import webview
from utils.common import (
    get_screen_size,
    callback_loading_html,
    callback_error_html,
    check_url_is_valid,
)
from utils.create_tray import TrayIcon
from utils.js_api import JsApi
from config.config import Config
from utils.ctreate_app import start_server_thread


def shown_hadeller(window):
    """
    @说明:shown事件处理,load_url到启动的服务url中
    @参数:
    @参数:
    @时间:2025/10/27 16:01:23
    @作者:Sean
    @返回:
    """
    if Config.development:
        # 开发环境
        valite_url = "http://127.0.0.1:5751/"
        print("开发环境 pnpm dev前端:", valite_url)
        window.load_url(valite_url)
    else:
        current_url = window.get_current_url()
        if current_url is None:
            valite_url = f"http://127.0.0.1:{port}"
            result = check_url_is_valid(valite_url)
            if result:
                try:
                    pyi_splash.close()  # 关闭闪屏
                    window.show()
                except Exception as e:
                    print(e)
                window.load_url(valite_url)
            else:
                window.load_html(callback_error_html())


if __name__ == "__main__":
    # TODO  启动窗口居中显示
    # 加入启动闪屏能力
    # 导入闪屏模块
    try:
        import pyi_splash  # type: ignore 加入行，忽略pylance警告

    except ImportError:
        # 如果不在PyInstaller打包环境中运行，则忽略
        pyi_splash = None
    port = Config.devPort if Config.development else Config.port
    print("端口", f"http://127.0.0.1:{port}")
    start_server_thread(port)
    title = Config.appName
    initWidth, initHeight, minWidth, minHeight = get_screen_size(webview=webview)
    api = JsApi()
    window = webview.create_window(
        title,
        html=callback_loading_html(),
        frameless=True,
        width=initWidth,
        height=initHeight,
        easy_drag=False,
        text_select=False,
        js_api=api,
        min_size=(minWidth, minHeight),
        background_color="#f2f2f2",
        zoomable=True,
    )
    window.events.shown += shown_hadeller  # 挂载上就执行
    # 创建托盘图标
    tray = TrayIcon(title, window)
    tray_icon = tray.create_tray()
    tray.run()
    # jsapi设置window
    api.set_window(window, tray_icon, title)
    # 创建gui类型 是否支持win7  win7使用cef 其他使用默认的gui
    gui = "cef" if Config.isWin7 else None
    # private_mode设置False  关闭后storage仍然存在
    webview.start(
        debug=Config.debug,
        private_mode=False,
        gui=gui,
        storage_path=Config.storage_path,
    )
